// pages/xuecar/signup.js
var util = require('../../utils/util.js');
const app = getApp();
var currentTime, interval;
var clickflag = 1;
var submitclick = 1;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        listInfo: [],
        showTopTips: false,
        errorMsg: "",
        bannerUrl:'',
        teachers: [],
        teacherIndex: 0,
        areas: [],
        areaIndex: 0,
        towns: [],
        townIndex: 0,
        schools: [],
        schoolIndex: 0,
        mobile:'',
        time: '获取验证码', //倒计时 
        currentTime: 61,
        noshow:true,
        isshow:true,
        flag:'quick',
        teachername:'',
        areaname: '',
        aid:0,
        townid:0,
        schoolname: '',
        sid:0,
        tid:0,
        showModalStatus: false,
        animationData: '',
        submitname:'预约教练', 
        isLoginAuth:false
    }, /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (!app.globalData.isLoginAuth) {
          this.showModal();
        }
        this.setData({
          isLoginAuth: app.globalData.isLoginAuth
        })
        
        if(options.tid>0){
          this.setData({
            isshow: false,
            flag: 'isteacher',
            tid:options.tid
          })
        }
        else{
          this.getAreas();
        }
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
      var uid = wx.getStorageSync('userId');
      wx.request({
        url: app.globalData.hostUrl + 'member/getfansinfo',
        data: {
          id: uid
        },
        success: function (res) {
          var name = res.data.result.realname;
          var mobile = res.data.result.phone;
          if (name == '' || mobile == '') {
            wx.showModal({
              content: '对不起，请先填写【个人资料】中的真实姓名和手机号码！',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '../myself/info',
                  })
                }
              }
            });
          }
        }
      })
      if (this.data.tid >0){
        this.getTeacherinfobytid();
      }
      this.setData({
        listInfo: app.globalData.listInfo
      })
      this.initBanner();
    },
    //广告图片初始化
    initBanner: function () {
        var that = this;
        var requrl = app.globalData.hostUrl + 'common/banner';
        var imgbanner = wx.getStorageSync('signupBanner');
        //console.log(imgbanner.length);
        if (!app.expiratTime('signupBanner') || imgbanner.length == 0) {
            wx.request({
                url: requrl,
                data: { 'location': '202' },
                header: {
                    'grant-appid': app.globalData.appid
                },
                success: function (res) {
                    if (res.statusCode === 200) {
                        wx.setStorageSync('signupBanner', res.data.result[0].imgpath);
                        that.setData({
                            bannerUrl: res.data.result[0].imgpath
                        })
                    }
                }
            })
        }
        else {
            that.setData({
                bannerUrl: imgbanner
            })
        }
    },
    getTeacherinfobytid:function(){
      var that=this;
      var requrl = app.globalData.hostUrl + 'common/TeacherByrid';
      wx.request({
        url: requrl,
        data: { 'tid': this.data.tid },
        header: {
          'grant-appid': app.globalData.appid
        },
        success: function (res) {
          //console.log(res);
          if (res.data.code == 200) {
              that.setData({
                teachername: res.data.result[0].realname,
                areaname: res.data.result[0].areaname,
                schoolname: res.data.result[0].schoolname,
                aid: res.data.result[0].aid,
                townid: res.data.result[0].townid,
                sid: res.data.result[0].sid
              })
          }
        }
      })
    },
    changeVal: function (e) {
        var that = this;
        this.setData({
            mobile: e.detail.value
        })
        util.clearError(that);
    },
    clearErrtip:function(){
      var that = this;
      util.clearError(that);
    },
    formSubmit:function(e){
        var that=this;
        var name = e.detail.value.name;
        var code = e.detail.value.code;
        if (this.data.flag=='quick'){
           // console.log(this.data.areaIndex);
            // if (this.data.areaIndex>0)
            //     var areaid = this.data.areaslist[this.data.areaIndex-1].id;
            // else{
            //     util.isError("选择报名区域!", that);
            //     return false;
            // }    
            // if (this.data.townIndex > 0)
            //   var townid = this.data.townslist[this.data.townIndex - 1].id;
            // else {
            //   util.isError("选择报名区域!", that);
            //   return false;
            // }  
        }
        else{
            var areaid=this.data.aid;
            var townid = this.data.townid;
        }
        var phone = this.data.mobile;
        var myreg = /^(14[0-9]|13[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$$/;
        if (phone == '') {
            util.isError("手机号不为空!", that);
            return false;
        } else if (!myreg.test(phone)) {
            util.isError("请输入正确的手机号!", that);
            return false;
        } 
        if (name == '') {
            util.isError("姓名不为空!", that);
            return false;
        }
        if (code == '') {
            util.isError("验证码不为空!", that);
            return false;
        }
        
        var postdata={
            'name':name,
            'code':code,
            'mobile':phone,
            'area':areaid,
            'townid': townid,
            'openid': wx.getStorageSync('openId'),
            'userid': wx.getStorageSync('userId'),
            'flag':this.data.flag,
            'formid': e.detail.formId
        }
        if (this.data.flag != 'quick'){
          postdata['sid'] = this.data.sid;
          postdata['tid'] = this.data.tid;
        }
        if(submitclick==1){
         
          submitclick=0;
          var requrl = app.globalData.hostUrl + 'handler/checkOrder';
          wx.request({
            url: requrl,
            data: { 'userid': wx.getStorageSync('userId'),'isexist':1 },
            success: function (res) {
              if (res.data.code == -1) {
                  var xcurl = app.globalData.hostUrl + 'handler/learnCar';
                  wx.request({
                    url: xcurl,
                      data: postdata,
                      header: {
                          'Content-Type': 'application/x-www-form-urlencoded',
                          'grant-appid': app.globalData.appid
                      },
                      method: 'POST',
                      success: function (res) {
                          //console.log(res);
                          if (res.data.code == 200) {
                              wx.navigateTo({
                                  url: '../xuecar/orderdetail?oid=' + res.data.result.stt
                              })
                          }
                          else{
                              util.isError(res.data.result, that);
                          }
                      }
                  })
              }
              else{
                wx.showModal({
                  title: '提示',
                  content: '您的学车订单已经存在，请查看目前状态',
                  success(res) {
                    wx.navigateTo({
                      url: '/pages/myself/myappointment'
                    })
                  }
                })
              }
            }
          })
        }
    },
    calling: function (e) {
      var mobile = '15916351997';
      wx.makePhoneCall({
        phoneNumber: mobile,
        success: function () {
          //console.log("拨打电话成功！")
        },
        fail: function () {
          // console.log("拨打电话失败！")
        }
      })
    },
    //获取手机验证码
    getSncode:function(){
        var that=this;
        var phone = this.data.mobile;
        var myreg = /^(14[0-9]|13[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$$/;
        if(phone==''){
            util.isError("手机号不为空!", that);
            return false;
        } else if (!myreg.test(phone)) {
            util.isError("请输入正确的手机号!", that);
            return false;
        } 

        var requrl = app.globalData.hostUrl + 'common/sendsms';
        if(clickflag==1){
            util.clearError(that);
            clickflag=0;
            currentTime = that.data.currentTime
            interval = setInterval(function () {
                currentTime--;
                that.setData({
                    time: currentTime + '秒'
                })
                if (currentTime <= 0) {
                    clearInterval(interval)
                    that.setData({
                        time: '重新发送',
                        currentTime: 61,
                    })
                    clickflag = 1;
                }
            }, 1000);

            wx.request({
                url: requrl,
                data:{
                    'phone': phone
                },
                header: {
                    'grant-appid': app.globalData.appid
                },
                success: function (res) {
                    //console.log(res);
                    if (res.data.code == 200) {
                        wx.showToast({
                            title: '验证码已发送!',
                            icon: 'none',
                            duration: 2000
                        })
                    } else {
                        util.isError('获取失败,' + res.data.result, that);
                        return;
                    }
                    clickflag = 1;
                }
            })            
        }
    },
    getAreas:function(){
        var that = this;
       
        var requrl = app.globalData.hostUrl + 'common/getAreas';
        var areasArr = ['-请选择-'];

        wx.request({
            url: requrl,
            success: function (res) {
                // console.log(res);
                if (res.statusCode === 200) {
                    var areaslist = res.data.result;
                    var areasMap = areaslist.map(item => {
                        return item.name;
                    });
                    areasArr = areasArr.concat(areasMap);
                    that.setData({
                        areas: areasArr,
                        areaslist
                    });
                }
            }
        })
        
    },
    getTowns: function () {
      var that = this;
      var requrl = app.globalData.hostUrl + 'common/getTwopids';
      var townsArr = ['-请选择-'];
      var aindex = this.data.areaIndex;
      if (parseInt(aindex) > 0) {
        aindex = parseInt(aindex) - 1;
        var aid = this.data.areaslist[aindex].id;
        wx.request({
          url: requrl,
          data: { 'pid': aid },
          header: {
            'grant-appid': app.globalData.appid
          },
          success: function (res) {
           // console.log(res);
            if (res.statusCode === 200) {
              var townslist = res.data.result;
              var townsMap = townslist.map(item => {
                return item.name;
              });
              townsArr = townsArr.concat(townsMap);
              that.setData({
                towns:townsArr,
                townslist
              });
            }
          }
        })
      }

    },
    getSchools:function(){
        var that = this;
        var requrl = app.globalData.hostUrl + 'common/SchoolByArea';
        var aindex =this.data.areaIndex;
        if (parseInt(aindex)>0){
            aindex = parseInt(aindex) - 1;
            var aid = this.data.areaslist[aindex].id;
            wx.request({
                url: requrl,
                data: { 'aid': aid },
                header: {
                    'grant-appid': app.globalData.appid
                },
                success: function (res) {
                    // console.log(res);
                    var schoollist = res.data.result;
                    var schools = schoollist.map(item => {
                        return item.sname;
                    });
                    that.setData({
                        schools: schools,
                        schoollist
                    });
                    //关联获取老师列表
                    if(schoollist.length>0){
                        that.getTeachers();
                    }
                    
                }
            })
        }
    },
    getTeachers: function () {
        var that = this;
        var requrl = app.globalData.hostUrl + 'common/TeacherByrid';
        var sindex = this.data.schoolIndex;
        
        var sid = this.data.schoollist[sindex].id;
        wx.request({
            url: requrl,
            data: { 'sid': sid ,page:1,psize:500},
            header: {
                'grant-appid': app.globalData.appid
            },
            success: function (res) {
                //console.log(res);
                var teacherlist = res.data.result;
                var teachers = teacherlist.map(item => {
                    return item.realname;
                });
                that.setData({
                    teachers: teachers,
                    teacherlist
                });
            }
        })
        
    },
    bindareasChange: function (e) {
       // console.log('picker country 发生选择改变，携带值为', e.detail.value);
        this.setData({
            schools: [],
            teachers: []
        });
        this.setData({
            areaIndex: e.detail.value
        })
        if(this.data.flag!='quick')
          this.getSchools();
        else
          this.getTowns();  
    },
    bindtownsChange: function (e) {
      // console.log('picker country 发生选择改变，携带值为', e.detail.value);
      this.setData({
        schools: [],
        teachers: []
      });
      this.setData({
        townIndex: e.detail.value
      })
    },
    bindschoolsChange: function (e) {
        //console.log('picker country 发生选择改变，携带值为', e.detail.value);
        this.setData({
            schoolIndex: e.detail.value
        })
        this.getTeachers();
    },
    bindteachersChange: function (e) {
        //console.log('picker country 发生选择改变，携带值为', e.detail.value);

        this.setData({
            teacherIndex: e.detail.value
        })
    },
  gohome: function () {
    wx.redirectTo({
      url: '../index/index',
    })
  },
  yuy: function () {
    if (1 == wx.getStorageSync('roleidentity')) {
      wx.redirectTo({
        url: '../myself/thappointment',
      })
    }
    else {
      wx.redirectTo({
        url: '../myself/myappointment',
      })
    }
  },
  orders: function () {
    if (1 == wx.getStorageSync('roleidentity')) {
      wx.redirectTo({
        url: '../myself/trorder',
      })
    }
    else {
      wx.redirectTo({
        url: '../myself/myorder',
      })
    }
  },
  mys: function () {
    wx.redirectTo({
      url: '../myself/myself',
    })
  },
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "ease-in-out",
      delay: 0
    })
    this.animation = animation
    animation.translateY(500).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  hideModal: function () {
    this.setData({
      showModalStatus: false,
    })
  },
  bindGetUserInfo: function (e) {
    console.log(e);
    if (e.detail.errMsg == 'getUserInfo:ok') {
      app.globalData.userInfo = e.detail.userInfo;
      app.getfansinfo();
    }
    else if (e.detail.errMsg == "getUserInfo:fail auth deny") {
     
    }
    else {
      wx.redirectTo({
        url: '../xuecar/index',
      })
    }
  }
})